<?php

namespace App\Http\Controllers\Admin\newWork;

use App\Http\Config\ErrorCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ChangeController extends CommonController
{
    private $tableName = "new_work_change";
    private $listTableName = "new_work_list";
    private $catTableName = "new_work_cat";
    private $typeTableName = "new_work_type";
    private $workReplyTableName = "new_work_reply";
    private $memberTableName = "member";
    private $adminUserTableName = "admin_users";
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    // 转单列表
	public function getPageList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $params = $request->post();
        $pageNo = isset($params["pageNo"]) ? $params["pageNo"] : 1;
        $pageSize = isset($params["pageSize"]) ? $params["pageSize"] : 10;
        $db = DB::table($this->tableName. " as wc")->leftJoin("{$this->listTableName} as l",'wc.list_id','=','l.id')
            ->leftJoin("{$this->typeTableName} as t",'t.id','=','l.type_id')
            ->leftJoin("{$this->catTableName} as c",'c.id','=','t.cat_id')
            ->leftJoin("{$this->adminUserTableName} as u",'u.id','=','wc.present_id')
            ->leftJoin("{$this->adminUserTableName} as u1",'u1.id','=','wc.new_id')
            ->select("wc.id", "u.name as presentAdminName", "u.mobile as  presentAdminMobile", "c.name as catName",
                "t.name as typeName", "wc.remark", "wc.create_time", "wc.update_time", "u1.name as newAdminName", "l.status as workStatus", "wc.status")
            ->where("wc.mall_id", $request->mallData['id']);
        if(!empty($params["search"])){
            $db->where(function ($query) use ($params) {
                $query->where('u.name', 'LIKE', '%' . $params["search"] . '%')
                    ->orwhere('u.mobile', 'LIKE', '%' . $params["search"] . '%');
            });
        }
        if(!empty($params["status"])){
            $db->where("wc.status", $params["status"]);
        }
        if(!empty($params["catId"])){
            $db->where("l.cat_id", $params["catId"]);
        }
        if(!empty($params["startTime"]) && !empty($params["endTime"])){
            $params["startTime"] = is_numeric($params["startTime"]) ? date("Y-m-d H:i:s", $params["startTime"]) : $params["startTime"];
            $params["endTime"] = is_numeric($params["endTime"]) ? date("Y-m-d H:i:s", $params["endTime"]) : $params["endTime"];
            $db->whereBetween('wc.create_time',[$params['startTime'],$params['endTime']]);
        }
        $data = array(
            'total' => $db->count(),
            'rows' => $db->skip(($pageNo-1) * $pageSize)->take($pageSize)->orderBy("wc.create_time", "desc")->get()
        );
        $data['rows'] = $this->transferFields(json_decode(json_encode($data['rows']),true));
        foreach ($data['rows'] as &$item){
            if(empty($item["presentAdminName"])){
                if(empty($admin)) {
                    $admin = DB::table($this->adminUserTableName)->where("position", "超级管理员")->orWhere("id", 1)->select("name", "mobile")->first();
                    $admin = json_decode(json_encode($admin), true);
                    $admin = $admin ? $admin : ["name" => "管理员", "mobile" => ""];
                }
                    $item["presentAdminName"] = $admin["name"];
                $item["presentAdminMobile"] = $admin["mobile"];
            }
        }
        $this->returnData['data'] = $data;
        return $this->return_result($this->returnData);
    }

    public function getInfo(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(empty($request->id)){
            return $this->return_result(ErrorCode::$admin_enum["customized"], "转单ID不能为空");
        }
        $data = DB::table($this->tableName. " as c")
            ->leftJoin("{$this->listTableName} as l",'c.list_id','=','l.id')
            ->leftJoin("{$this->typeTableName} as t",'t.id','=','l.type_id')
            ->leftJoin("{$this->catTableName} as cat",'cat.id','=','t.cat_id')
            ->leftJoin("{$this->memberTableName} as m",'l.user_id','=','m.id')
            ->leftJoin("{$this->adminUserTableName} as a",'c.present_id','=','a.id')
            ->leftJoin("{$this->adminUserTableName} as u1",'u1.id','=','c.new_id')
            ->select("l.id as listId", "m.name as memberName", "m.mobile as memberMobile", "a.name as userName", "a.mobile as userMobile",
                "c.create_time", "c.status", "c.remark", "c.reason", "u1.name as newAdminName", "u1.mobile as newAdminMobile", "c.update_time",
                "l.create_time as workCreateTime", "l.status as workStatus", "cat.name as catName", "t.name as typeName", "l.feedback")
            ->where("c.id", $request->id)->first();
        $data = json_decode(json_encode($data),true);
        $data["feedback"] = json_decode($data["feedback"], true);
        foreach ((array)$data["feedback"] as $key => &$f){
            if($f["type"] == "UploadPicture" && !empty($f["reply"])){
                $reply = $f["reply"];
                $f["reply"] = [];
                if(is_array($reply)){
                    foreach ($reply as $tt){
                        $f["reply"][] = ["id" => $tt, "url" => $this->processingPictures($tt)];
                    }
                }else{
                    $f["reply"] = ["id" => $reply, "url" => $this->processingPictures($reply)];
                }
            }
        }
        // 反馈记录
        $replyData = DB::table($this->workReplyTableName . " as r")
            ->leftJoin("{$this->adminUserTableName} as u",'u.id','=','r.user_id')
            ->select("r.feedback", "r.picture", "r.annex", "r.create_time", "u.name")
            ->orderBy("r.create_time", "desc")
            ->where("list_id", $data["listId"])->get();
        $replyData = $this->transferFields(json_decode(json_encode($replyData),true));
        foreach ($replyData as &$item){
            $item["annex"] = @json_decode($item["annex"]);
            $pic = explode(",", $item["picture"]);
            $item["picture"] = [];
            foreach ($pic as $i){
                $item["picture"][] = ["id" => $i, "url" => $i];
            }
        }
        $data["replyData"] = $replyData;
        $this->returnData['data'] = $this->transferFields($data);
        return $this->return_result($this->returnData);
    }

    public function refuse(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(empty($request->id)){
            return $this->return_result(ErrorCode::$admin_enum["customized"], "转单ID不能为空");
        }
        if(empty($request->reason)){
            return $this->return_result(ErrorCode::$admin_enum["customized"], "驳回理由不能为空");
        }
        $changeData = DB::table($this->tableName)->where("id", $request->id)->select("list_id")->first();
        if(empty($changeData)){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '工单不存在';
            return $this->return_result($this->returnData);
        }
        if(DB::table($this->tableName)->where("id", $request->id)->update(["reason" => $request->reason, "status" => 3, "update_time" => date("Y-m-d H:i:s")])){
            DB::table($this->listTableName)->where("id", $changeData->list_id)->update(["is_transfer" => "0"]);
        }else{
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '驳回失败';
        }
        return $this->return_result($this->returnData);
    }

    public function agree(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(empty($request->id)){
            return $this->return_result(ErrorCode::$admin_enum["customized"], "转单ID不能为空");
        }
        if(empty($request->userId)){
            return $this->return_result(ErrorCode::$admin_enum["customized"], "转单人员不能为空");
        }
        $changeData = DB::table($this->tableName)->where("id", $request->id)->select("list_id")->first();
        if(empty($changeData)){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '工单不存在';
            return $this->return_result($this->returnData);
        }
        if(DB::table($this->tableName)->where("id", $request->id)->update([
            "status" => 2, "new_id" => $request->userId, "update_time" => date("Y-m-d H:i:s")
        ])){
            DB::table($this->listTableName)->where("id", $changeData->list_id)->update([
                "is_transfer" => "0", "receive_time" => date("Y-m-d H:i:s"), "receive_id" => $request->userId
            ]);
        }else{
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '驳回失败';
        }
        return $this->return_result($this->returnData);
    }
}